package valuecomusa.fijibus.eticket.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import valuecomusa.fijibus.eticket.db.shorthaul.GpsDBHandler;
import valuecomusa.fijibus.eticket.shorthaul.R;
import valuecomusa.fijibus.eticket.Declarations;
import valuecomusa.fijibus.eticket.InputFilterMinMax;
import valuecomusa.fijibus.eticket.Utilities;
import valuecomusa.fijibus.eticket.WorkingSession;
import valuecomusa.fijibus.eticket.db.shorthaul.BusinessDBHandler;
import valuecomusa.fijibus.eticket.ws.MemberValue;
import valuecomusa.fijibus.eticket.ws.TransactionValue;

import java.util.Date;


public class refund extends Activity
{
    TransactionValue refundableTransaction;
    Button submit;
    private GpsDBHandler gpsDb;
    int inputNoCard;
    private BusinessDBHandler db;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
        gpsDb = new GpsDBHandler(refund.this);
        Intent input = getIntent();
        inputNoCard = input.getIntExtra("OPTION_NO_CARD", 0);
        WorkingSession.getInstance().currentActivity = refund.this;
        if(inputNoCard == 1)
            setContentView(R.layout.refund_nocard);
        else
		    setContentView(R.layout.refund);
        //---
        db = new BusinessDBHandler(this);
        //---
        ((TextView) findViewById(R.id.refund_error_text)).setText("");
        //--
        submit = (Button) findViewById(R.id.refund_submit);
        submit.setOnClickListener(onSubmitClick);

        Button btn = (Button) findViewById(R.id.refund_cancel);
        btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                //cancel refund
                InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);

                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);

                onBackPressed();
            }
        });

        EditText transactionIdEdit = (EditText) findViewById(R.id.refund_transaction_id);
        transactionIdEdit.setOnFocusChangeListener(onTransactionIDFocusChanged);

        if(inputNoCard == 1)
            return;

        TextView customerId = (TextView)findViewById(R.id.refund_customer_id);
        customerId.setText(WorkingSession.getInstance().currentPassenger.getFullName());

        refundableTransaction = db.getLastCheckedOutTransaction(
                WorkingSession.getInstance().currentPassenger.ISN);
        if(refundableTransaction == null || refundableTransaction.isRefunded != 0)
        {
            WorkingSession.getInstance().ShowToast(this, "Could not get refundable transaction", Toast.LENGTH_LONG);
            onBackPressed();
            return;
        }
        //---------------
        // --set amount allow input range
        EditText amountEdit = (EditText) findViewById(R.id.refund_amount);
        amountEdit.setFilters(new InputFilter[] { new InputFilterMinMax(0f, refundableTransaction.FareAmount) });
        //--
        RadioButton x = (RadioButton) findViewById(R.id.refund_paybycard);
        RadioButton y = (RadioButton) findViewById(R.id.refund_paybycash);
        if(refundableTransaction.Type.equals("BMF"))  //BMF card
        {
            x.setChecked(true);
        }
        else if(refundableTransaction.Type.equals("Cash") //Cash
                || refundableTransaction.Type.equals("Cash-TopUp")) //Cash-TopUp
        {
            y.setChecked(true);
        }
        x.setEnabled(false);
        y.setEnabled(false);

        TextView lbl = (TextView)findViewById(R.id.refund_max_value_label);
        lbl.setText(String.format("(maximum %s)",
                WorkingSession.getInstance().decimalFormat.format(refundableTransaction.FareAmount)));

	}

    /*@Override
    public void onBackPressed()
    {
        Intent mainScreen = new Intent(refund.this, Main.class);
        startActivity(mainScreen);
    }*/

    private View.OnClickListener onSubmitClick = new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            InputMethodManager inputManager = (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE);

            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
            //set refund value
            //set require print receipt
            //finish
            EditText et = (EditText) findViewById(R.id.refund_transaction_id);

            String inputTransactionID = et.getText().toString();

            if(inputTransactionID.trim().length() == 0)
            {
                ShowError("Please enter Transaction ID");
                return;
            }

            if(inputNoCard == 1)
            {
                refundableTransaction = db.getCheckedOutTransactionByID(inputTransactionID);
                if(refundableTransaction == null)
                {
                    ShowError("Invalid Transaction ID");
                    return;
                }
                MemberValue memberValue = db.getMemberByISN(refundableTransaction.MemberISN);
                if(memberValue == null)
                {
                    ShowError("Passenger not found");
                    return;
                }
                WorkingSession.getInstance().currentPassenger = memberValue;
            }

            if(!inputTransactionID.equals(refundableTransaction.TransactionID))
            {
                ShowError("Invalid Transaction ID");
                return;
            }
            et = (EditText) findViewById(R.id.refund_amount);
            String inputAmount = et.getText().toString();
            if(inputAmount.length() == 0)
            {
                ShowError("Please enter refund amount");
                return;
            }

            //CheckBox print_receipt = (CheckBox)findViewById(R.id.refund_print_receipt);
            doRefund(Double.parseDouble(inputAmount), true);
        }
    };

    private void doRefund(double amount, boolean printReceipt)
    {
        try
        {
            submit.setEnabled(false);
            //---
            String transType = "";
            if(refundableTransaction.Type.equals("BMF"))  //BMF card

            {
                transType = "BMF";
            }
            else if(refundableTransaction.Type.equals("Cash") //Cash
                    || refundableTransaction.Type.equals("Cash-TopUp")) //Cash-TopUp
            {
                transType = "Cash";
            }

            TransactionValue trans = WorkingSession.getInstance().CreateTransaction(
                    refund.this,
                    "REFUND",
                    transType,
                    amount, //amount
                    0, 0,
                    0, //topUp amount
                    null, //voucher
                    null, null,
                    0,
                    0, 0, 0, 0, 0, 0,
                    null,
                    refundableTransaction.TransactionID);

            //--
            if(trans == null)
            {
                WorkingSession.getInstance().ShowErrorDialog(
                        refund.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );
                submit.setEnabled(true);
                return;
            }
         //       WorkingSession.getInstance().SAMUpdateCardBalance((float)WorkingSession.getInstance().currentPassenger.CurrentBalance,
           //             (float) gpsDb.getCurrentLocation(WorkingSession.getInstance().setupJournal.ISN).Latitude,
             //           (float)gpsDb.getCurrentLocation(WorkingSession.getInstance().setupJournal.ISN).Longitude);

            //--
            BusinessDBHandler db = new BusinessDBHandler(refund.this);
            try
            {
                long rx = db.addTransaction(trans);
                trans.ISN = (int)rx;
                rx = db.setTransactionIsRefunded(refundableTransaction.ISN);
            }
            catch (Exception ex)
            {
                WorkingSession.getInstance().ShowErrorDialog(
                        refund.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );
                submit.setEnabled(true);
                return;
            }

            WorkingSession.getInstance().ShowToast(refund.this, "Add transaction successful", Toast.LENGTH_SHORT);
            //---
            if(refundableTransaction.Type.equals("BMF")  //BMF card
                    || refundableTransaction.Type.equals("Cash-TopUp")) //Cash-TopUp
            {
                WorkingSession.getInstance().currentPassenger.CurrentBalance += amount;
                int x = db.updateMemberBalance(
                        WorkingSession.getInstance().currentPassenger.ISN,
                        WorkingSession.getInstance().currentPassenger.CurrentBalance);
                if(x > 0)
                    WorkingSession.getInstance().ShowToast(refund.this, "Update customer balance successful", Toast.LENGTH_SHORT);
                else
                    WorkingSession.getInstance().ShowToast(refund.this, "Update customer balance failed", Toast.LENGTH_SHORT);
            }

            // print receipt
            if (printReceipt)
            {
                if(!PrintReceipt(trans))
                    onBackPressed();
            }
            else
                onBackPressed();
        }
        catch (Exception ex)
        {
            WorkingSession.getInstance().ShowToast(refund.this, ex.getMessage(),
                    Toast.LENGTH_LONG);
        }
    }

    private String CreateReceiptContent(TransactionValue xx)
    {
        Date date = new Date();
        String receiptDate = Utilities.DateToString(date, "dd/MM/yyyy");
        String receiptTime = Utilities.DateToString(date, "hh:mm a");

        /*String content = "Powered by: BulamyFiji (BMF)"
                + "\nSunbeam Transport (Fiji) Ltd"
                + "\nLautoka, Fiji Islands"
                + "\nTIN #: 35846990930"
                + "\n********************************"
                + "\nDate     : " + receiptDate
                + "\nDept Time: " + receiptTime
                + "\nRefund   : " + WorkingSession.getInstance().decimalFormat.format(xx.FareAmount)
                + "\nOrg ID   : " + xx.Description
                + "\n---"
                + "\nTran ID  : " + xx.TransactionID
                + "\nVehicle  : " + WorkingSession.getInstance().journalBus.BusNumber
                + "\nConductor: " + WorkingSession.getInstance().loggedInConductor.UserName
                + "\n---"
                + "\nCustomer : " + WorkingSession.getInstance().currentPassenger.getFullName()
                + "\nACC #    : xxxx" + WorkingSession.getInstance().currentPassenger.CardNumber.substring(
                WorkingSession.getInstance().currentPassenger.CardNumber.length()-4)
                + "\nBalance  : " + WorkingSession.getInstance().decimalFormat.format(
                WorkingSession.getInstance().currentPassenger.CurrentBalance)
                + "\n********************************"
                + "\nThank you"
                + "\n--------------------------------\n";*/

        String content = /*Utilities.StringAlignCenter(48, "BulaMy(Fiji) - BMF etikite  ") //+ "\n"
                + Utilities.StringAlignCenter(48, "BMF Make It Your Choice")
                + Utilities.StringAlignCenter(48, "www.bulamyfiji.com")
                + "\n\n"*/
                Utilities.StringAlignLeftRight(48,
                    "Refund Amount: " + WorkingSession.getInstance().decimalFormat.format(xx.FareAmount),
                    "Bus Reg.: " + WorkingSession.getInstance().journalBus.BusNumber
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "Transaction ID: " +  xx.TransactionID,
                    "Driver: " + WorkingSession.getInstance().journalDriver.FullName
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "Org ID: " + xx.Description,
                    "Company: DeeCees Fiji Ltd"
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "ACCT Name: " +  (inputNoCard == 1? "" :
                            WorkingSession.getInstance().currentPassenger.getFullName()),
                    "TIN: 12683467161"
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "ACCT #: " +  (inputNoCard == 1? "" :
                            WorkingSession.getInstance().currentPassenger.CardNumber),
                    "Issued: " + receiptDate
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "Balance: " +  (inputNoCard == 1? "" :
                            WorkingSession.getInstance().decimalFormat.format(
                                WorkingSession.getInstance().currentPassenger.CurrentBalance)
                    ),
                    receiptTime
                ) + "\n"
                + "\nThank you\n\n";

        return content;
    }

    private boolean PrintReceipt(TransactionValue xx)
    {
        Date date = new Date();

        String content = CreateReceiptContent(xx);

        int rs = WorkingSession.getInstance().PreparePrintReceiptWifi(refund.this, content, printReceiptCallback);

        if (rs == Declarations.NO_WIFI_PRINTER_SETUP)
            WorkingSession.getInstance().ShowToast(refund.this, "No printer selected. Please setup one.", Toast.LENGTH_LONG);
        else if (rs == Declarations.PRINT_RECEIPT_ERROR)
        {
            WorkingSession.getInstance().ShowToast(refund.this, "Print receipt failed.", Toast.LENGTH_LONG);
        }
        return rs == Declarations.PRINT_RECEIPT_WAITING;
    }

    /*private final Handler printReceiptCallback = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case Declarations.BLUETOOTH_CONNECTING:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Connecting to printer...", Toast.LENGTH_SHORT);
                    break;
                case Declarations.BLUETOOTH_CONNECTED:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Connect successful", Toast.LENGTH_SHORT);
                    break;
                case Declarations.BLUETOOTH_UNABLE_CONNECT:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Unable connect to printer", Toast.LENGTH_SHORT);
                    onBackPressed();
                    break;
                case Declarations.PRINT_RECEIPT_ERROR:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Print receipt failed", Toast.LENGTH_SHORT);
                    onBackPressed();
                    break;
                case Declarations.PRINT_RECEIPT_SUCCESSFUL:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Print receipt successful", Toast.LENGTH_SHORT);
                    onBackPressed();
                    break;
            }
        }
    };*/

    private final Handler printReceiptCallback = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
				case Declarations.WIFI_PRINTER_CONNECTED:
					WorkingSession.getInstance().ShowToast(refund.this,
							"Printer connected", Toast.LENGTH_SHORT);
					WorkingSession.getInstance().PrintReceipt();
					break;
                case Declarations.WIFI_PRINTER_CONNECTED_ERR:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Unable connect to printer", Toast.LENGTH_SHORT);
                    break;
                case Declarations.WIFI_PRINTER_SEND_FAILED:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Unable send data to printer", Toast.LENGTH_SHORT);
                    break;
                case Declarations.PRINT_RECEIPT_SUCCESSFUL:
                    WorkingSession.getInstance().ShowToast(refund.this,
                            "Print receipt successful", Toast.LENGTH_SHORT);
                    onBackPressed();
                    break;
            }
        }
    };

    private void ShowError(String msg)
    {
        TextView errorText = (TextView) findViewById(R.id.refund_error_text);
        if(errorText != null)
            errorText.setText(msg);
    }

    private View.OnFocusChangeListener onTransactionIDFocusChanged = new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean hasFocus)
        {
            if(view.getId() == R.id.refund_transaction_id && !hasFocus && inputNoCard == 1)
            {
                String inputValue = ((EditText)findViewById(R.id.refund_transaction_id)).getText().toString().trim();
                if(inputValue.length() == 0)
                    return;
                //find refundable transaction
                refundableTransaction = db.getCheckedOutTransactionByID(inputValue);
                if(refundableTransaction != null)
                {
                    TextView lbl = (TextView)findViewById(R.id.refund_max_value_label);
                    lbl.setText(String.format("(maximum %s)",
                            WorkingSession.getInstance().decimalFormat.format(refundableTransaction.FareAmount)));
                    //--
                    EditText amountEdit = (EditText) findViewById(R.id.refund_amount);
                    amountEdit.setFilters(new InputFilter[] { new InputFilterMinMax(0f, refundableTransaction.FareAmount) });
                }
            }
        }
    };
}
